package com.qiaofang.applet.service.other.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.base.MongoBaseService;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.constants.PropertyTradeTypeConstants;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.constants.switchConfigConstants;
import com.qiaofang.applet.service.member.domain.Department;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.repository.DepartmentRepository;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.EmployeeListDto;
import com.qiaofang.applet.service.member.service.dto.EmployeeQueryDto;
import com.qiaofang.applet.service.other.domain.*;
import com.qiaofang.applet.service.other.repository.CorporationRepository;
import com.qiaofang.applet.service.other.service.*;
import com.qiaofang.applet.service.other.service.dto.*;
import com.qiaofang.applet.service.property.domain.Estate;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.service.EstateDetailService;
import com.qiaofang.applet.service.property.service.EstateService;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.druid.util.Utils.md5;

/**
 * Created by IDEA.
 *
 * @auther Zym.
 * @company qiaofang
 * @date 2020/9/12 11:35
 */
@Service
@Slf4j
public class CorporationServiceImpl extends MongoBaseService<Corporation, String> implements CorporationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CorporationRepository corporationRepository;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private DictCorpService dictCorpService;

    @Autowired
    private LendingRatesService lendingRatesService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private EstateDetailService estateDetailService;

    @Autowired
    private TopicService topicService;

    @Autowired
    private AssetsService assetsService;

    @Autowired
    private EstateService estateService;

    @Autowired
    private RedisUtil redisUtil;

    private static RestTemplate restTemplate = new RestTemplate();

    public CorporationServiceImpl(CorporationRepository repository) {
        super(repository);
        this.corporationRepository = repository;
    }

    @Override
    public String saveCorporation(Corporation corporationSave) {
        String corporationCode = corporationSave.getCorporationCode();
        String webDomain = corporationSave.getWebDomain();
        if (StringUtils.isEmpty(corporationCode)) {
            throw new BusinessException("集团代码为空");
        }
        if (StringUtils.isEmpty(webDomain)) {
            throw new BusinessException("官网域名为空");
        }
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (StringUtils.isEmpty(corporationSave.getId()) && corporation != null) {
            throw new BusinessException("集团代码已存在，不可新增");
        }
        Corporation corporationByDomain = corporationRepository.findOneByWebDomain(webDomain);
        if (corporationByDomain != null && !corporationByDomain.getId().equals(corporationSave.getId())) {
            throw new BusinessException("官网域名已存在");
        }
        if (StringUtils.isEmpty(corporationSave.getId())) {
            corporationSave.setDeleted(false);
            corporationRepository.insert(corporationSave);
            dictCorpService.initCorporationData(corporationCode);
            //初始化房贷利率
            lendingRatesService.initLendingRates(corporationCode);
        } else {
            String oldWebDomain = corporation.getWebDomain();
            String[] ignoreProperties=new String[] {"propertyRules", "firsthandRules", "baiduSearchEngine", "employeeLabelList","privacyAgreement","PCprivacyAgreement","deleted"};
            BeanUtils.copyProperties(corporationSave,corporation,ignoreProperties);
            updateById(corporation);
            // 清理缓存
            if(!oldWebDomain.equals(corporation.getWebDomain())) {
                cityCompanyService.clearDomainCache(corporation.getCorporationCode());
            }
        }
        //TODO 生成授权链接
        return "ok";
    }

    @Override
    public boolean removeCorporation(String id) {
        Corporation corporation = mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), Corporation.class);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
//        Integer authStatus = corporation.getAuthStatus();
//        Date submitAuthTime = corporation.getSubmitAuthTime();
//        if (authStatus != null && submitAuthTime != null){
//            throw new BusinessException("该集团有授权信息，不可删除");
//        }
        corporation.setDeleted(true);
        corporation.setUpdateTime(new Date());
        corporationRepository.save(corporation);
//        cityCompanyService.removeCompanyByCorp(corporation.getCorporationCode());
//        dictCorpService.removeCorporationData(corporation.getCorporationCode());
        // 清理缓存
        cityCompanyService.clearDomainCache(corporation.getCorporationCode());
        return true;
    }

    @Override
    public Corporation getCorporationByCorporationCode(String corporationCode) {
        return corporationRepository.findOneByCorporationCode(corporationCode);
    }

    @Override
    public void initCorporationPrivacyAgreement(Corporation corporation) {
        ClassPathResource resource = new ClassPathResource("corporation/privacyAgreement.txt");
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = resource.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            //原有的内容
            String navigationBarTitle = "navigationBarTitle";
            String corporationName = "corporationName";
            //要替换的内容
            String replaceStr = corporation.getNavigationBarTitle();
            String replaceStrName = corporation.getCorporationName();
            String line = null;
            while ((line = br.readLine()) != null) {
                // 替换每行中, 符合条件的字符串
                line = line.replaceAll(navigationBarTitle, replaceStr);
                line = line.replaceAll(corporationName, replaceStrName);
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("获取集团隐私协议数据文件失败", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("获取集团隐私协议数据文件失败", e);
            }
            try {
                br.close();
            } catch (IOException e) {
                log.error("获取集团隐私协议数据文件失败", e);
            }
        }
        try {
            corporation.setPrivacyAgreement(sb.toString());
            updateById(corporation);
        } catch (Exception e) {
            log.error("集团初始化隐私协议文件转换异常，数据格式错误", e);
        }
    }

    @Override
    public void initCorporationPCPrivacyAgreement(Corporation corporation) {
        ClassPathResource resource = new ClassPathResource("corporation/PcPrivacyAgreement.txt");
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = resource.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            //原有的内容
            String navigationBarTitle = "navigationBarTitle";
            String corporationName = "corporationName";
            //要替换的内容
            String replaceStr = corporation.getNavigationBarTitle();
            String replaceStrName = corporation.getCorporationName();
            String line = null;
            while ((line = br.readLine()) != null) {
                // 替换每行中, 符合条件的字符串
                line = line.replaceAll(navigationBarTitle, replaceStr);
                line = line.replaceAll(corporationName, replaceStrName);
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("获取集团隐私协议数据文件失败", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("获取集团隐私协议数据文件失败", e);
            }
            try {
                br.close();
            } catch (IOException e) {
                log.error("获取集团隐私协议数据文件失败", e);
            }
        }
        try {
            corporation.setPCprivacyAgreement(sb.toString());
            updateById(corporation);
        } catch (Exception e) {
            log.error("集团初始化隐私协议文件转换异常，数据格式错误", e);
        }
    }

    @Override
    public PropertyRules getPropertyRules(String corporationCode) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        return corporation.getPropertyRules();
    }

    @Override
    public FirsthandRules getFirsthandRules(String corporationCode) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        return corporation.getFirsthandRules();
    }

    @Override
    public void updatePropertyRules(String corporationCode, PropertyRules propertyRules) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (propertyRules != null && propertyRules.equals(corporation.getPropertyRules())) {
            return;
        }
        corporation.setPropertyRules(propertyRules);
        corporation.setUpdateTime(new Date());
        corporationRepository.save(corporation);
        log.info("更改二手房、租房上下架规则成功，集团名：{}，本次规则详情：{}，更改时间：{}", corporation.getCorporationName(), propertyRules.toString(), corporation.getUpdateTime());
        Criteria criteria = new Criteria();
        criteria.and("corporationCode").is(corporationCode);
        //只对有效房源进行上下架处理
        criteria.and("tradeStatus").is("有效");
        Update update = new Update();
        update.set("rulesHandle", false);
        mongoTemplate.updateMulti(new Query().addCriteria(criteria), update, Property.class);
    }

    @Override
    public void updateFirsthandRules(String corporationCode, FirsthandRules firsthandRules) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (firsthandRules != null && firsthandRules.equals(corporation.getFirsthandRules())) {
            return;
        }
        corporation.setFirsthandRules(firsthandRules);
        corporation.setUpdateTime(new Date());
        corporationRepository.save(corporation);
        log.info("更改新房上下架规则成功，本次规则详情：{}，更改时间：{}", firsthandRules.toString(), corporation.getUpdateTime());
        Criteria criteria = new Criteria();
        criteria.and("corporationCode").is(corporationCode);
        //售罄楼盘不进行上下架处理
        criteria.and("saleStatus").ne("6");
        Update update = new Update();
        update.set("rulesHandle", false);
        mongoTemplate.updateMulti(new Query().addCriteria(criteria), update, FirsthandEstate.class);
    }

    @Override
    public void incrementAddToDict() {
        try {
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("deleted", match -> match.exact())
                    .withIgnoreNullValues();
            Corporation corporation = new Corporation();
            corporation.setDeleted(Boolean.FALSE);
            Iterable<Corporation> list = corporationRepository.findAll(Example.of(corporation, matcher));

            // 从init.json读取所有系统配置参数
            ClassPathResource resource = new ClassPathResource("corporation/init.json");
            String initStr = IOUtils.toString(resource.getInputStream(), "UTF-8");
            List<DictCorp> initList = JSON.parseArray(initStr, DictCorp.class);

            // 循环所有集团增量初始化新参数
            list.forEach(item -> {
                dictCorpService.incrementAddToDict(item.getCorporationCode(), initList);
                lendingRatesService.initLendingRates(item.getCorporationCode());
            });
        } catch (Exception e) {
            log.error("批量更新字典参数异常", e);
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            }
            throw new BusinessException(e);
        }
    }

    @Override
    public CommerceAcademyDto getCommerceAcademyConfig() {

        CommerceAcademyDto commerceAcademyDto = new CommerceAcademyDto();
        Corporation corporation = corporationRepository.findOneByCorporationCode(QfContextHolder.getContext().getCorporationCode());
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }

        log.info("corporation commerceAcademy is:{}", corporation.getSwitchConfig().getCommerceAcademy());
        if (corporation.getSwitchConfig().getCommerceAcademy() == null) {
            commerceAcademyDto.setOpen(Boolean.FALSE);
            return commerceAcademyDto;
        } else if (corporation.getSwitchConfig().getCommerceAcademy().equals(switchConfigConstants.CLOSED.getValue())) {
            commerceAcademyDto.setOpen(Boolean.FALSE);
            return commerceAcademyDto;
        }

        if (StringUtils.isBlank(corporation.getJumpUrl())
                || StringUtils.isBlank(corporation.getCommerceAppId())) {
            throw new BusinessException("请检查商学院跳转配置");
        }
        commerceAcademyDto.setOpen(Boolean.TRUE);
        commerceAcademyDto.setCommerceAppId(corporation.getCommerceAppId());
        commerceAcademyDto.setJumpUrl(corporation.getJumpUrl());
        commerceAcademyDto.setMenuName(StringUtils.defaultString(corporation.getMenuName()));
        return commerceAcademyDto;
    }

    @Override
    public String getEmployeeReply(String corporationCode) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
        return StringUtils.isNotBlank(corporation.getEmployeeReplyParams()) ? corporation.getEmployeeReplyParams() : "";
    }

    @Override
    public void updateEmployeeReply(String corporationCode, String params) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
        corporation.setEmployeeReplyParams(params);
        updateById(corporation);
    }

    @Override
    public String getAutoEmployeeReply(String employeeUniqueUuid, String memberId) {

        String memberChatKey = RedisKeyUtil.getMemberChatKey(employeeUniqueUuid, memberId);

        Object object = redisUtil.get(memberChatKey);
        if (object != null) {
            return "";
        }

        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
        //规则
        String employeeReplyParams = corporation.getEmployeeReplyParams();
        if (StringUtils.isBlank(employeeReplyParams)) {
            return null;
        }
        Employee employee = employeeService.findByEmployeeUniqueUuid(employeeUniqueUuid);
        if (employee == null) {
            throw new BusinessException("该经纪人不存在");
        }
        String deptName = employee.getDeptName();
        if (StringUtils.isEmpty(deptName)) {
            Department department = departmentRepository.findByCorporationCodeAndDeptUuid(corporationCode, employee.getDeptUuid());
            if (department != null) {
                deptName = department.getDeptName();
            }
        }
        String[] templateParam = {"{{公司名}}", "{{门店}}", "{{人名}}", "{{手机号}}"};
        String[] dynamicParam = {corporation.getCorporationName(), deptName, employee.getEmployeeName(), StringUtils.defaultString(employee.getMobilePhone(), "暂无手机号")};
        String replyParams = StringUtils.replaceEachRepeatedly(employeeReplyParams, templateParam, dynamicParam);
        String replace = StringUtils.replace(replyParams, "\n", "<br/>");
        redisUtil.setToDayEnd(memberChatKey, replace);
        return replace;

    }

    @Override
    public JSONObject getMiniProgramPath(Map<String, Object> params, String url, String appId, String appKey) {
        try {
            HttpHeaders headers = headers(appId, appKey);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

            ResponseEntity<String> response = restTemplate.postForEntity(url + "/atool/getMiniProgramPath", new HttpEntity<>(params, headers), String.class);
            String responseBody = response.getBody();
            JSONObject json = JSON.parseObject(responseBody);
            log.info("getMiniProgramPath http result:{}", responseBody);
            if ("1".equals(json.getString("responseCode"))) {
                JSONObject data = JSON.parseObject(json.getString("data"));
                if (data != null) {
                    return data;
                }
            }
        } catch (RestClientException e) {
            log.error("getMiniProgramPath error == > ", e);
        }
        return null;
    }

    /**
     * 生成接口header
     *
     * @return
     */
    private HttpHeaders headers(String appId, String appKey) {
        //获取时间
        String timeSign = String.valueOf(System.currentTimeMillis());
        //设置签名
        String signature = md5(appId + appKey + timeSign);
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", appId);
        headers.add("timeSign", timeSign);
        headers.add("signature", signature);
        return headers;
    }

    @Override
    public String getServerTemplateId() {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
        return corporation.getTemplateId();
    }

    @Override
    public List<EmployeeLabel> getEmployeeLabelList(String corporationCode) {
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        if (corporation == null) {
            throw new BusinessException("该集团不存在");
        }
        List<EmployeeLabel> employeeLabelList = corporation.getEmployeeLabelList();
        if (CollectionUtils.isEmpty(employeeLabelList)) {
            List<EmployeeLabel> labelList = new ArrayList<>();
            labelList.add(new EmployeeLabel("", "不限"));
            return labelList;
        }
        employeeLabelList.add(0, new EmployeeLabel("", "不限"));
        return employeeLabelList;
    }

    @Override
    public WebsiteIncludeInfoDto getWebsiteIncludeInfo(WebsiteIncludeInfoReqDto reqDto) {
        WebsiteIncludeInfoDto websiteIncludeInfoDto = new WebsiteIncludeInfoDto();

        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        String cityCode = reqDto.getCityCode();
        String pageName = reqDto.getPageName();
        String businessUuid = reqDto.getBusinessUuid();

        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        CityCompany cityCompany = cityCompanyService.getCompanyByCityAndCorp(cityCode, corporationCode);
        if (corporation == null || cityCompany == null) {
            throw new BusinessException("无法获取集团或公司信息");
        }
        String cityName = cityCompany.getCompanyCity();
        String corporationName = corporation.getCorporationName();
        String slogan = cityCompany.getSlogan();
        String pcWebBigTile = StringUtils.defaultString(corporation.getPcWebBigTile(), "在这儿寻找到你的家");
        String pcWebLittleTile = StringUtils.defaultString(corporation.getPcWebLittleTile(), "每一次归来 都承载着美好期许");
        Property property;
        String keyword;
        switch (pageName) {

            //首页
            case "index":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "房地产信息网-二手房-租房-新房「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "," + cityName + corporationName + "," + cityName + "二手房," + cityName + "租房," + cityName + "新房,"
                                + cityName + "房地产信息网," + pcWebLittleTile + "," + pcWebBigTile)
                        .build();
                break;
            //二手房列表
            case "secondHandPropertyList":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "二手房「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "," + cityName + "二手房出售," + cityName + "二手房房源," + cityName + "二手房买卖," + cityName + "二手房交易")
                        .build();
                break;
            //二手房详情
            case "secondHandPropertyDetail":
                property = propertyService.findByPropertyUniqueUuid(businessUuid);
                if (property == null) {
                    return websiteIncludeInfoDto;
                }
                SalePropertyDetailDto saleDetailDto = propertyMapper.domainToSaleDetailDto(property);
                //【小区名称】，【商圈】，【户型】，【楼层】，总面积【面积】，【建房年代】建成，【装修情况】，朝【朝向】，【售价】
                keyword = saleDetailDto.getEstateName() + "," + saleDetailDto.getAreaName() + "," + saleDetailDto.getHouseType() + ","
                        + saleDetailDto.getFloorRange() + "," + "总面积" + bigDecimal2Long(saleDetailDto.getSquare()) + "平米," + saleDetailDto.getCompleteYear()
                        + "建成," + saleDetailDto.getDecoration() + ",朝" + saleDetailDto.getDirection() + "," + bigDecimal2Long(saleDetailDto.getSellUnitPrice()) + "元/平米";
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(saleDetailDto.getTitle())
                        .description(saleDetailDto.getPropertyDepictTitle())
                        .keyword(keyword.replaceAll("null", ""))
                        .build();
                break;
            //租房列表
            case "rentPropertyList":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "租房「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "," + cityName + "房源出租," + cityName + "租房信息," + cityName + "出租房网," + cityName + "房屋出租价格")
                        .build();
                break;
            //租房详情
            case "rentPropertyDetail":
                property = propertyService.findByPropertyUniqueUuid(businessUuid);
                if (property == null) {
                    return websiteIncludeInfoDto;
                }
                RentPropertyDetailDto rentDetailDto = propertyMapper.domainToRentDetailDto(property);
                //【小区名称】，【商圈】，【户型】，【楼层】，总面积【面积】，【建房年代】建成，【装修情况】，朝【朝向】，【租价】
                keyword = rentDetailDto.getEstateName() + "," + rentDetailDto.getAreaName() + "," + rentDetailDto.getHouseType() + ","
                        + rentDetailDto.getFloorRange() + "," + "总面积" + bigDecimal2Long(rentDetailDto.getSquare()) + "平米," + rentDetailDto.getCompleteYear()
                        + "建成," + rentDetailDto.getDecoration() + ",朝" + rentDetailDto.getDirection() + "," + bigDecimal2Long(rentDetailDto.getRentPrice()) + "元/月";
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(rentDetailDto.getTitle())
                        .description(rentDetailDto.getPropertyDepictTitle())
                        .keyword(keyword.replaceAll("null", ""))
                        .build();
                break;
            //新房列表
            case "firstHandPropertyList":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "新房「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "," + cityName + "楼盘," + cityName + "新楼盘," + cityName + "新房房价")
                        .build();
                break;
            //新房详情
            case "firstHandPropertyDetail":
                FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(businessUuid);
                if (firsthandEstate == null) {
                    return websiteIncludeInfoDto;
                }
                //【楼盘名称】，【商圈】，【物业类型】，【均价】，【项目特色】
                keyword = firsthandEstate.getEstateName() + "," + firsthandEstate.getAreaName() + "," + firsthandEstate.getPropertyType()
                        + "," + bigDecimal2Long(firsthandEstate.getAveragePrice()) + "元/平米," + firsthandEstate.getFeatureType();
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(firsthandEstate.getEstateName() + "-" + cityName + "楼盘「" + corporationName + "」")
                        .description(firsthandEstate.getEstateDesc())
                        .keyword(keyword.replaceAll("null", ""))
                        .build();
                break;
            //小区列表
            case "estateList":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "小区「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "小区," + cityName + "小区房价,"
                                + cityName + "小区排名排行榜," + cityName + "小区二手房")
                        .build();
                break;
            //小区详情页、小区房源列表页、小区相册页
            case "estateDetail":
            case "estatePropertyList":
            case "estateAlbumList":
                EstateEditDto estateEditDto = estateDetailService.getEstateEditDetail(businessUuid);
                String estateName = estateEditDto.getEstateName();
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(estateName + "-" + cityName + "二手房-租房「" + corporationName + "」")
                        .description(estateEditDto.getIntroduction())
                        .keyword(estateName + "," + cityName + estateName + "," + estateName + "二手房," + estateName + "房价," + estateName + "租房")
                        .build();
                break;
            //主题房源列表页
            case "topicPropertyList":
                Topic topic = topicService.getDomainById(businessUuid);
                if (topic == null) {
                    return websiteIncludeInfoDto;
                }
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(topic.getTopicName() + "-" + cityName + topic.getTopicType() + "-"
                                + topic.getTopicTitle() + "「" + corporationName + "」")
                        .description(topic.getTopicPresent())
                        .keyword(topic.getTopicName() + "," + cityName + topic.getTopicType() + ","
                                + cityName + topic.getTopicType() + "房价")
                        .build();
                break;
            //经纪人首页
            case "employeeIndex":
                Employee employee = employeeService.findByEmployeeUniqueUuid(businessUuid);
                if (employee == null) {
                    return websiteIncludeInfoDto;
                }
                EmployeeListDto listDto = employeeService.domainToListDto(employee);
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(listDto.getEmployeeName() + "-" + cityName + listDto.getDeptName()
                                + "-买房租房咨询「" + corporationName + "」")
                        .description(listDto.getRecommendDescribe())
                        .keyword(cityName + "," + listDto.getDeptName() + ",买新房,买二手房,租房,价格咨询,买房咨询,租房咨询")
                        .build();
                break;
            //资讯列表
            case "assertsList":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "房产资讯「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "房产资讯," + cityName + "二手房资讯," + cityName + "新房资讯," + cityName + "租房资讯," + corporationName + "资讯")
                        .build();
                break;
            //资讯详情
            case "assertsDetail":
                Optional<Assets> optional = assetsService.findById(businessUuid);
                if (!optional.isPresent()) {
                    return websiteIncludeInfoDto;
                }
                Assets assets = optional.get();
                AssetsType assetsType = assetsService.findAssetsType(assets.getAssetsTypeId());
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityName + "房产资讯-" + assets.getAssetsTitle() + "「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "房产资讯," + assetsType.getAssetsTypeName() + "," + assets.getAssetsTitle() + "," + corporationName + "资讯")
                        .build();
                break;
            //公司介绍页
            case "corporationInfo":
                websiteIncludeInfoDto = WebsiteIncludeInfoDto.builder()
                        .title(cityCompany.getCompanyName() + "-" + cityName + "房地产信息网「" + corporationName + "」")
                        .description(slogan)
                        .keyword(cityName + "," + cityCompany.getCompanyName() + "," + cityName + corporationName + "," + cityName + "二手房,"
                                + cityName + "租房," + cityName + "新房," + cityName + "房地产信息网," + pcWebBigTile + "," + pcWebLittleTile)
                        .build();
                break;


        }
        return websiteIncludeInfoDto;
    }

    @Override
    public Set<String> getSeoUrlSet(SearchIncludeQueryDto queryDto) {
        if (queryDto == null || StringUtils.isEmpty(queryDto.getCorporationCode()) || queryDto.getPageSize() == 0
                || StringUtils.isEmpty(queryDto.getWebDomain()) || CollectionUtils.isEmpty(queryDto.getCityCodeList())) {
            throw new BusinessException("入参不能为空");
        }
        Set<String> urlSet = new HashSet<>();
        String corporationCode = queryDto.getCorporationCode();
        int pageSize = queryDto.getPageSize();
        String index = "http://" + queryDto.getWebDomain();
        urlSet.add(index);
        for (String cityCode : queryDto.getCityCodeList()) {
            urlSet.add(index + "/secondHouse/" + cityCode + "/" + corporationCode + "/list");
            urlSet.add(index + "/newHouse/" + cityCode + "/" + corporationCode + "/list");
            urlSet.add(index + "/rentingHouse/" + cityCode + "/" + corporationCode + "/list");
            urlSet.add(index + "/community/" + cityCode + "/" + corporationCode + "/list");
            urlSet.add(index + "/information/" + cityCode + "/" + corporationCode + "/list");
            urlSet.add(index + "/companyprofile/" + cityCode + "/" + corporationCode + "/list");

            //获取主题列表前n条，并收录所有主题房源URL
            List<Topic> topicList = topicService.findByParams(TopicQueryDto.builder().corporationCode(corporationCode)
                    .cityCode(cityCode).build(), PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(topicList)) {
                for (Topic topic : topicList) {
                    String topicType = topic.getTopicType();
                    Set<String> uniqueUuids = topic.getUniqueUuids();
                    switch (topicType) {
                        case "新房":
                            urlSet.add(index + "/newHouse/" + cityCode + "/" + corporationCode + "/" + topic.getId());
                            if (!CollectionUtils.isEmpty(uniqueUuids)) {
                                for (String uniqueUuid : uniqueUuids) {
                                    urlSet.add(index + "/newHouseDetail/" + cityCode + "/" + corporationCode + "/" + uniqueUuid);
                                }
                            }
                            break;
                        case "二手房":
                            urlSet.add(index + "/secondHouse/" + cityCode + "/" + corporationCode + "/" + topic.getId());
                            if (!CollectionUtils.isEmpty(uniqueUuids)) {
                                for (String uniqueUuid : uniqueUuids) {
                                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + uniqueUuid + "/1?type=1");
                                }
                            }
                            break;
                        case "租房":
                            urlSet.add(index + "/rentingHouse/" + cityCode + "/" + corporationCode + "/" + topic.getId());
                            if (!CollectionUtils.isEmpty(uniqueUuids)) {
                                for (String uniqueUuid : uniqueUuids) {
                                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + uniqueUuid + "/2?type=2");
                                }
                            }
                            break;
                    }
                }
            }

            //获取主推经纪人前n条
            List<Employee> employeeList = employeeService.findAllByParams(EmployeeQueryDto.builder().corporationCode(corporationCode)
                    .cityCode(cityCode).recommend(true).build(), PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(employeeList)) {
                for (Employee employee : employeeList) {
                    urlSet.add(index + "/agent/" + cityCode + "/" + corporationCode + "/" + employee.getEmployeeUniqueUuid());
                }
            }

            //获取资讯前n条
            Criteria criteriaAssets = Criteria.where("corporationCode").is(corporationCode).and("cityCodes").in(cityCode);
            List<Assets> assetsList = mongoTemplate.find(new Query(criteriaAssets).with(PageRequest.of(0, pageSize)), Assets.class);
            if (!CollectionUtils.isEmpty(assetsList)) {
                for (Assets assets : assetsList) {
                    urlSet.add(index + "/informationDetail/" + cityCode + "/" + corporationCode + "/" + assets.getId());
                }
            }

            //获取主推新房前n条
            //获取新房前n条
            List<FirsthandEstate> firsthandList = firsthandEstateService.findAllByParams(FirsthandEstateQueryDto.builder().corporationCode(corporationCode)
                    .cityCode(cityCode).upDownFlag(UpDownFlagConstants.UP_FLAG.getValue()).build(), PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(firsthandList)) {
                for (FirsthandEstate firsthandEstate : firsthandList) {
                    urlSet.add(index + "/newHouseDetail/" + cityCode + "/" + corporationCode + "/" + firsthandEstate.getEstateUniqueUuid());
                }
            }
            firsthandList = firsthandEstateService.findAllHotFirsthandByParams(FirsthandEstateQueryDto.builder().corporationCode(corporationCode)
                    .cityCode(cityCode).recommend(true).upDownFlag(UpDownFlagConstants.UP_FLAG.getValue()).build(), PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(firsthandList)) {
                for (FirsthandEstate firsthandEstate : firsthandList) {
                    urlSet.add(index + "/newHouseDetail/" + cityCode + "/" + corporationCode + "/" + firsthandEstate.getEstateUniqueUuid());
                }
            }

            //获取主推二手房前n条
            //获取二手房前n条
            SalePropertyQueryDto salePropertyQueryDto = new SalePropertyQueryDto();
            salePropertyQueryDto.setCorporationCode(corporationCode);
            salePropertyQueryDto.setCityCode(cityCode);
            salePropertyQueryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());
            List<Property> saleList = propertyService.findAllSaleByParams(salePropertyQueryDto, PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(saleList)) {
                for (Property property : saleList) {
                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + property.getPropertyUniqueUuid() + "/1?type=1");
                }
            }
            salePropertyQueryDto.setRecommend(true);
            saleList = propertyService.findAllHotSaleByParams(salePropertyQueryDto, PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(saleList)) {
                for (Property property : saleList) {
                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + property.getPropertyUniqueUuid() + "/1?type=1");
                }
            }

            //获取主推租房
            //获取租房
            RentPropertyQueryDto rentPropertyQueryDto = new RentPropertyQueryDto();
            rentPropertyQueryDto.setCorporationCode(corporationCode);
            rentPropertyQueryDto.setCityCode(cityCode);
            rentPropertyQueryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());
            List<Property> rentList = propertyService.findAllRentByParams(rentPropertyQueryDto, PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(rentList)) {
                for (Property property : rentList) {
                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + property.getPropertyUniqueUuid() + "/2?type=2");
                }
            }
            rentPropertyQueryDto.setRecommend(true);
            rentList = propertyService.findAllHotRentByParams(rentPropertyQueryDto, PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(rentList)) {
                for (Property property : rentList) {
                    urlSet.add(index + "/houseDetail/" + cityCode + "/" + corporationCode + "/" + property.getPropertyUniqueUuid() + "/2?type=2");
                }
            }

            //获取小区列表
            List<Estate> estateList = estateService.findAllEstateByParams(EstateQueryDto.builder().corporationCode(corporationCode)
                    .cityCode(cityCode).build(), PageRequest.of(0, pageSize)).getContent();
            if (!CollectionUtils.isEmpty(estateList)) {
                for (Estate estate : estateList) {
                    urlSet.add(index + "/communityHome/" + cityCode + "/" + corporationCode + "/" + estate.getEstateUniqueUuid());
                    if (estate.getSaleNum() > 0) {
                        urlSet.add(index + "/communityList/" + cityCode + "/" + corporationCode + "/" + estate.getEstateUniqueUuid() + "?estateName=" + estate.getEstateName() + "&listType=在售");
                    }
                    if (estate.getRentNum() > 0) {
                        urlSet.add(index + "/communityList/" + cityCode + "/" + corporationCode + "/" + estate.getEstateUniqueUuid() + "?estateName=" + estate.getEstateName() + "&listType=在租");
                    }
                }
            }

        }
        return urlSet;
    }

    private Long bigDecimal2Long(BigDecimal bigDecimal) {
        if (bigDecimal == null) {
            return 0L;
        }
        return bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
    }

    @Override
    public List<CorporationReportDto> getCorporationReportList() {
        List<Corporation> corporationList = mongoTemplate.find(new Query().addCriteria(Criteria.where("deleted").is(false)), Corporation.class);
        if (CollectionUtils.isEmpty(corporationList)){
            return new ArrayList<>();
        }
        List<CorporationReportDto> list = new LinkedList<>();
        for (Corporation corporation : corporationList) {
            list.add(CorporationReportDto.builder()
                    .corporationCode(corporation.getCorporationCode())
                    .corporationName(corporation.getCorporationName())
                    .empLabelNum(Long.parseLong(corporation.getEmployeeLabelList().size()+ ""))
                    .build());
        }

        Aggregation aggAssets = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        AggregationResults result = mongoTemplate.aggregate(aggAssets, "other_assets", CorporationSumResultDto.class);
        List<CorporationSumResultDto> resultList = result.getMappedResults();
        Map<String, Long> assetsSumMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation aggTopic = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(aggTopic, "other_topic", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> topicSumMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation saleTotal = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.SALE)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(saleTotal, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> saleTotalMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation saleUp = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.SALE)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)
                        .and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue())),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(saleUp, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> saleUpMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation saleHot = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.SALE)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)
                        .and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue()).and("recommend").is(true)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(saleHot, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> saleHotMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation rentTotal = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.RENT)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(rentTotal, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> rentTotalMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation rentUp = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.RENT)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)
                        .and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue())),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(rentUp, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> rentUpMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation rentHot = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("tradeType").in(PropertyTradeTypeConstants.ALL, PropertyTradeTypeConstants.RENT)
                        .and("square").ne(null).and("sellPrice").ne(null).and("sellUnitPrice").ne(null)
                        .and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue()).and("recommend").is(true)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(rentHot, "property_property", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> rentHotMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));



        Aggregation firstTotal = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("averagePrice").ne(null)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(firstTotal, "property_firsthand_estate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> firstTotalMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation firstUp = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("averagePrice").ne(null).and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue())),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(firstUp, "property_firsthand_estate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> firstUpMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation firstHot = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("averagePrice").ne(null).and("upDownFlag").is(UpDownFlagConstants.UP_FLAG.getValue()).and("recommend").is(true)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(firstHot, "property_firsthand_estate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> firstHotMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation estateTotal = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(estateTotal, "property_estate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> estateTotalMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation empTotal = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(empTotal, "member_employee", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> empTotalMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation empHot = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("recommend").is(true)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(empHot, "member_employee", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> empHotMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation shareSale = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("operateType").is(2).and("businessType").is(2)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(shareSale, "member_member_operate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> shareSaleMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation shareRent = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("operateType").is(2).and("businessType").is(3)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(shareRent, "member_member_operate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> shareRentMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation shareFirst = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("operateType").is(2).and("businessType").is(1)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(shareFirst, "member_member_operate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> shareFirstMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation shareEmp = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("operateType").is(2).and("businessType").is(4)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(shareEmp, "member_member_operate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> shareEmpMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));



        Aggregation inspection = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("status").is(1)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(inspection, "member_appointment", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> inspectionMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation appointment = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("status").is(0)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(appointment, "member_appointment", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> appointmentMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

        Aggregation member = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(member, "member_member", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> memberMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation exploreHouse = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("operateType").is(1).and("businessType").ne(4)),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(exploreHouse, "member_member_operate", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> exploreHouseMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation chat = Aggregation.newAggregation(
                Aggregation.match(new Criteria()),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(chat, "other_message_list", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> chatMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation subscribe = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deleted").is(false).and("subscribeStatus").is("订阅")),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(subscribe, "member_member_subscribe", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> subscribeMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));


        Aggregation subscribeCancel = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("deleted").is(false).and("subscribeStatus").is("取消订阅")),
                Aggregation.group("corporationCode").first("corporationCode").as("corporationCode")
                        .count().as("sum")
        );
        result = mongoTemplate.aggregate(subscribeCancel, "member_member_subscribe", CorporationSumResultDto.class);
        resultList = result.getMappedResults();
        Map<String, Long> subscribeCancelMap = resultList.stream().collect(Collectors.toMap(CorporationSumResultDto::getCorporationCode, CorporationSumResultDto::getSum, (k1, k2) -> k1));

//        log.info("============================各集团明细数据统计打印============================");

        for (CorporationReportDto corporationReportDto : list) {
            String corporationCode = corporationReportDto.getCorporationCode();
            corporationReportDto.setAssetsNum(assetsSumMap.get(corporationCode) == null ? 0L : assetsSumMap.get(corporationCode));
            corporationReportDto.setTopicNum(topicSumMap.get(corporationCode) == null ? 0L : topicSumMap.get(corporationCode));
            corporationReportDto.setSaleTotalNum(saleTotalMap.get(corporationCode) == null ? 0L : saleTotalMap.get(corporationCode));
            corporationReportDto.setSaleUpNum(saleUpMap.get(corporationCode) == null ? 0L : saleUpMap.get(corporationCode));
            corporationReportDto.setSaleHotNum(saleHotMap.get(corporationCode) == null ? 0L : saleHotMap.get(corporationCode));
            corporationReportDto.setRentTotalNum(rentTotalMap.get(corporationCode) == null ? 0L : rentTotalMap.get(corporationCode));
            corporationReportDto.setRentUpNum(rentUpMap.get(corporationCode) == null ? 0L : rentUpMap.get(corporationCode));
            corporationReportDto.setRentHotNum(rentHotMap.get(corporationCode) == null ? 0L : rentHotMap.get(corporationCode));
            corporationReportDto.setFirstTotalNum(firstTotalMap.get(corporationCode) == null ? 0L : firstTotalMap.get(corporationCode));
            corporationReportDto.setFirstUpNum(firstUpMap.get(corporationCode) == null ? 0L : firstUpMap.get(corporationCode));
            corporationReportDto.setFirstHotNum(firstHotMap.get(corporationCode) == null ? 0L : firstHotMap.get(corporationCode));
            corporationReportDto.setEstateTotalNum(estateTotalMap.get(corporationCode) == null ? 0L : estateTotalMap.get(corporationCode));
            corporationReportDto.setEmpTotalNum(empTotalMap.get(corporationCode) == null ? 0L : empTotalMap.get(corporationCode));
            corporationReportDto.setEmpHotNum(empHotMap.get(corporationCode) == null ? 0L : empHotMap.get(corporationCode));
            corporationReportDto.setShareSaleNum(shareSaleMap.get(corporationCode) == null ? 0L : shareSaleMap.get(corporationCode));
            corporationReportDto.setShareRentNum(shareRentMap.get(corporationCode) == null ? 0L : shareRentMap.get(corporationCode));
            corporationReportDto.setShareFirstNum(shareFirstMap.get(corporationCode) == null ? 0L : shareFirstMap.get(corporationCode));
            corporationReportDto.setShareEmpNum(shareEmpMap.get(corporationCode) == null ? 0L : shareEmpMap.get(corporationCode));
            corporationReportDto.setShareTotalNum(corporationReportDto.getShareFirstNum() + corporationReportDto.getShareSaleNum()
                    + corporationReportDto.getShareRentNum() + corporationReportDto.getShareEmpNum());
            corporationReportDto.setInspectionNum(inspectionMap.get(corporationCode) == null ? 0L : inspectionMap.get(corporationCode));
            corporationReportDto.setAppointmentNum(appointmentMap.get(corporationCode) == null ? 0L : appointmentMap.get(corporationCode));
            corporationReportDto.setMemberNum(memberMap.get(corporationCode) == null ? 0L : memberMap.get(corporationCode));
            corporationReportDto.setExploreHouseNum(exploreHouseMap.get(corporationCode) == null ? 0L : exploreHouseMap.get(corporationCode));
            corporationReportDto.setChatNum(chatMap.get(corporationCode) == null ? 0L : chatMap.get(corporationCode));
            corporationReportDto.setSubscribeNum(subscribeMap.get(corporationCode) == null ? 0L : subscribeMap.get(corporationCode));
            corporationReportDto.setSubscribeCancelNum(subscribeCancelMap.get(corporationCode) == null ? 0L : subscribeCancelMap.get(corporationCode));
            corporationReportDto.setAppointmentTotalNum(corporationReportDto.getInspectionNum() + corporationReportDto.getAppointmentNum());

//            System.out.println(corporationReportDto.getCorporationName() + "\t" +
//                    corporationReportDto.getAssetsNum() + "\t" + corporationReportDto.getTopicNum() + "\t" + corporationReportDto.getSaleTotalNum() + "\t" +
//                    corporationReportDto.getSaleUpNum() + "\t" + corporationReportDto.getSaleHotNum() + "\t" + corporationReportDto.getRentTotalNum() + "\t" +
//                    corporationReportDto.getRentUpNum() + "\t" + corporationReportDto.getRentHotNum() + "\t" + corporationReportDto.getFirstTotalNum() + "\t" +
//                    corporationReportDto.getFirstUpNum() + "\t" + corporationReportDto.getFirstHotNum() + "\t" + corporationReportDto.getEstateTotalNum() + "\t" +
//                    corporationReportDto.getEmpTotalNum() + "\t" + corporationReportDto.getEmpHotNum() + "\t" + corporationReportDto.getEmpLabelNum() + "\t" +
//                    corporationReportDto.getShareTotalNum() + "\t" + corporationReportDto.getShareSaleNum() + "\t" + corporationReportDto.getShareRentNum() + "\t" +
//                    corporationReportDto.getShareFirstNum() + "\t" + corporationReportDto.getShareEmpNum() + "\t" + corporationReportDto.getInspectionNum() + "\t" +
//                    corporationReportDto.getAppointmentNum() + "\t" + corporationReportDto.getMemberNum() + "\t" + corporationReportDto.getExploreHouseNum() + "\t" +
//                    corporationReportDto.getChatNum() + "\t" + corporationReportDto.getSubscribeNum() + "\t" + corporationReportDto.getSubscribeCancelNum() + "\t" +
//                    corporationReportDto.getAppointmentTotalNum());
        }

        return list;
    }
}
